package com.dapeng.lmssim.client.group;

import com.dapeng.lmssim.client.IMServiceConfiguration;
import com.dapeng.lmssim.client.IMServiceException;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

/**
 * @author songkaizong
 */
@FeignClient(name = "im-service",
        url = "http://localhost:8088",
        configuration = IMServiceConfiguration.class,
        fallbackFactory = GroupClient.GroupFallbackFactory.class)
public interface GroupClient {
    @GetMapping("/force-logout")
    void logout();

    @GetMapping("/groups/{id}")
    GroupInfo getGroup(@PathVariable String id);

    @DeleteMapping("/groups/{id}")
    void deleteGroup(@PathVariable String id);

    @PutMapping("/groups/{id}/owner")
    void updateOwner(@PathVariable String id, @RequestBody String userId);

    @Component
    @Slf4j
    class GroupFallbackFactory implements FallbackFactory<GroupClient> {

        @Override
        public GroupClient create(Throwable throwable) {
            return new GroupClient() {
                @Override
                public void logout() {
                    log.error("logout error:{}", throwable.getMessage());
                }

                @Override
                public GroupInfo getGroup(String id) {
                    log.error("调用im-service失败，message:{}", throwable.getMessage());
                    return new GroupInfo();
                }

                @Override
                public void deleteGroup(String id) {
                    log.error("deleteGroup error,{}", throwable.getMessage());
                    boolean is = throwable.getClass().getName().equals(IMServiceException.class.getName());
                    if (is) {
                        //自定义业务异常处理，如群组不可删除，可以解析出异常信息
                    } else {
                        //其他异常处理，如请求超时
                    }
                    // 如果失败是可接受的，自己通过增加补偿机制处理，
                    // 不可接受的，调用方增加事务，直接向上抛异常，整个操作失败，全局异常处理返回前端。
                    // throw new RuntimeException(throwable.getMessage());
                }

                @Override
                public void updateOwner(String id, String userId) {

                }
            };
        }
    }
}

